<?php
namespace addon\cms\controller;

use tpfcore\Core;
use app\common\controller\AddonBase;
use tpfcore\wxbizmsgcrypt\WXBizMsgCrypt;
use addon\wechat_fans\logic\WechatRequest;
//服务器配置接口地址 
/*define("TOKEN", "6a2sUegaHvbo91Z");       //定义token
define("WXPAY_APPID","wx6ec953e84c6159b8");     //替换为自己的APPID
define("WXPAY_APPSECRET","b6efe83142b5be6da229fcda37d33e9f"); //替换为自己的APPSECRET*/
class MiniService extends AddonBase
{
	public function _initialize(){
		parent::_initialize();
        self::initWechatConst();
		isset($this->param['echostr']) && self::valid();
	}

	public function index(){

        $XmlStr = file_get_contents('php://input');

        if(empty($XmlStr)){
            $this->err_log('XML原数据为空',$XmlStr);
            die('');
        }
        $wxparam = $this->param;
        if(!empty($wxparam) && is_array($wxparam)){
            try {
                $timestamp     = $wxparam['timestamp'];
                $nonce         = $wxparam['nonce'];
                $msg_signature = isset($wxparam['msg_signature'])?$wxparam['msg_signature']:'';
                $wechatEncode = new WXBizMsgCrypt(MIMICHAT_TOKEN,MIMICHAT_ENCODINGAESKEY,MIMICHAT_APPID);
                $decryptMsg   = '';  //解密后的明文
                $errCode      = $wechatEncode->decryptMsg($msg_signature,$timestamp,$nonce,$XmlStr,$decryptMsg);
                $XmlStr       = $decryptMsg;
                if($errCode != 0){
                    $this->err_log('解密失败',$errCode);
                }
            } catch (\Exception $e) {
                $this->err_log('解密异常',$e->getMessage());
            }

            $wx_log = 'timestamp:'.$timestamp.'=nonce:'.$nonce.'=msg_signature:'.$msg_signature;
            $this->wechat_log('额外数据：',$wx_log);
        }

        $encrypt_type  = (isset($wxparam['encrypt_type']) && ($wxparam['encrypt_type'] =='aes'))?'aes':'raw';

        $this->wechat_log('加密类型',$encrypt_type);

        file_put_contents('wechat_param.txt','处理后数据：'.$XmlStr.PHP_EOL,FILE_APPEND);

		$XmlObj = simplexml_load_string($XmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        //写入请求日志
        (new WechatRequest())->weChatRequestLog($XmlObj,$XmlStr);

        $this->wechat_log('事件类型',$XmlObj->MsgType);
        
        /*if($XmlObj->MsgType == 'text'){

            $data['touser'] = (String)$XmlObj->FromUserName ; // "oOTwQ5Xiz0v5TPmRfXLbukYMLf9w";
            $Content=(String)$XmlObj->Content;

            if($Content === '图文') {
                $data['msgtype'] = 'link';
                $data['link']['title'] = urlencode('文章标题');
                $data['link']['description'] = urlencode('好文章要分享');
                $data['link']['url'] = 'https://www.tpframe.com';
                $data['link']['thumb_url'] = 'https://www.bmob.cn/uploads/attached/app/logo/20180930/c02d430f-08b0-ec9c-d256-f14113dd5f90.PNG';
            }else if($Content === '1'){
                $data['msgtype'] = 'image';
                $data['image']['media_id'] = 'q3oQpLPWOIB50tCKdR510qeNIGEQd9A0Ku7DJJmsTsXVeQZqq0sUMK2gbUyJZsYn';
                $data['image']['picurl'] = 'this is image';
            }else if($Content === '2'){
                $data['msgtype'] = 'text';
                $data['text']['content'] = urlencode('你好');//urlencode 解决中文乱码问题
                
            }else{
                $data['msgtype'] = (String)$XmlObj->MsgType;

                $data['text']['content'] = urlencode('对不起，我不知道您在说什么....');//urlencode 解决中文乱码问题
            }

            $this->send($data);

            exit;
            
        }
        */

        try {
            switch ($XmlObj->MsgType) {
                case 'text':
                    $result = Core::loadAddonModel('MiniReceiveText')->receiveTextFunc($XmlObj);
                    break;
                case 'image':
                case 'link':
                case 'miniprogrampage':
                default:
                    die('<xml><ToUserName><![CDATA['.(String)$XmlObj->FromUserName.']]></ToUserName><FromUserName><![CDATA['.(String)$XmlObj->ToUserName.']]></FromUserName><CreateTime>'.(String)$XmlObj->CreateTime.'</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>');
            }
            if ($encrypt_type == 'aes'){

                $wechatEncode = new WXBizMsgCrypt(MIMICHAT_TOKEN,MIMICHAT_ENCODINGAESKEY,MIMICHAT_APPID);
                $encryptMsg   = '';
                $errCode      = $wechatEncode->encryptMsg($result, $timestamp, $nonce, $encryptMsg);
                $result       = $encryptMsg;
                if($errCode != 0){
                    $this->err_log('加密失败',$errCode);
                }
            }
            die($result);
        } catch (\Exception $e) {
            $this->err_log('程序错误',$e->getMessage());
        }
        die('');
	}

	//验证签名
   	protected function valid(){

		$echoStr   = $this->param['echostr'];
		$signature = $this->param['signature'];
		$timestamp = $this->param['timestamp'];
		$nonce     = $this->param['nonce'];
		$token     = MIMICHAT_TOKEN;
		$tmpArr    = array($token, $timestamp, $nonce);

        sort($tmpArr, SORT_STRING);
        $tmpStr = sha1(implode($tmpArr));

        if($tmpStr == $signature){
            file_put_contents('wechat_check.txt','验证成功,时间：'.date('Y-m-d H:i:s').'----随机串：'.$echoStr.PHP_EOL,FILE_APPEND);
            die($echoStr);
        }
        file_put_contents('wechat_check.txt','验证失败,时间：'.date('Y-m-d H:i:s').'----随机串：'.$echoStr.PHP_EOL,FILE_APPEND);
    }

    private function initWechatConst(){
        $config = config("config.mimi_program");

        if(empty($config['config']) || empty($config['config']['url']) || empty($config['config']['token'])  || empty($config['config']['encodingAESKey'])  || empty($config['config']['appid'])  || empty($config['config']['secret'])){
            die('配置不完整');
        }

        define('MIMICHAT_TOKEN', $config['config']['token']);   //令牌(Token)
        define('MIMICHAT_APPID', $config['config']['appid']);      //AppID
        define('MIMICHAT_APPSECRET', $config['config']['secret']);      //AppSecret
        define('MIMICHAT_ENCODINGAESKEY', $config['config']['encodingAESKey']);//消息加解密密钥
    }

    protected function err_log($msg='异常',$errCode=''){
        file_put_contents('wechat_error.txt','时间：'.date('Y-m-d H:i:s').'='.$msg.':'.$errCode.PHP_EOL,FILE_APPEND);
    }
    protected function wechat_log($msg='操作记录',$data=''){
        file_put_contents('wechat_log.txt','时间：'.date('Y-m-d H:i:s').'='.$msg.':'.$data.PHP_EOL,FILE_APPEND);
    }
}